<template>
  <Dividetb>
    <template #top>
      <TopBox :title="'文档管理'">
        <FilterSearch
          ref="filterSearchRef"
          :placeholder="'请输入文档名称'"
          :searchCallBack="searchCallBack"
        />
        <!-- <topButtonGroup :buttonList="tbuttonList" /> -->
        <topButtonGroupDoc :buttonList="tbuttonList" />
      </TopBox>
      <NewFile
        v-if="newFileVisible"
        :visible="newFileVisible"
        @callBack="newCallBack"
        @close="closeNewFile"
      />
      <AddToKnowledgeLib
        v-if="addToVisible"
        :visible="addToVisible"
        :name="addToFileName"
        structure="file"
        :callBack="addToCallback"
        @close="addToVisible = false"
      />
      <AddToTemplate
        v-if="addTemVisible"
        :visible="addTemVisible"
        :name="addToFileName"
        structure="file"
        :callBack="addTemCallback"
        @close="addTemVisible = false"
      />
    </template>
    <template #bottom>
      <div class="tableBox">
        <el-table
          class="listTable"
          :data="tableData"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          @cell-mouse-enter="cellMouseEnter"
          @cell-mouse-leave="cellMouseLeave"
          @selection-change="handleSelectionChange"
          @row-click="currentRowChange"
          @row-dblclick="openFile"
          ref="tableRef"
          @scroll="handleScroll"
          v-loading="isLoading"
        >
          <el-table-column
            width="30"
            class-name="zhiding"
            label-class-name="zhiding"
          >
            <template #default="scope">
              <el-icon v-if="scope.row.isTop == 1">
                <svg
                  t="1740105554250"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="888"
                  width="200"
                  height="200"
                >
                  <path
                    d="M572.72420125 170.92152889l388.03137422 346.41455786c20.47053369 23.81432605 24.9561088 56.32018205 11.89551218 84.8531001-13.04894578 28.54456889-40.69639965 46.19559822-72.04882205 46.19559822H758.29885155v241.75502222C758.29885155 957.81956267 703.13210311 1012.98631111 635.42904605 1012.98631111h-245.71630934c-67.69140622 0-122.85815467-55.1550976-122.85815466-122.85815466V648.39643591H124.53951715c-31.3524224 0-58.99987627-17.67433102-72.04882204-46.20724906-13.04894578-28.54456889-8.57502151-61.05042489 11.89551218-84.8531001l388.03137422-346.41455786a79.30729813 79.30729813 0 0 1 60.15330987-27.64745387c23.16187875 0 45.05381547 10.11293298 60.15330987 27.64745387zM348.76001849 566.47934862v323.66045867a41.06922667 41.06922667 0 0 0 40.95271822 40.94106738h245.71630934a41.06922667 41.06922667 0 0 0 40.95271822-40.95271822V566.47934862h218.59314346L512.57089138 226.58926365 130.16687502 566.47934862H348.77166933zM949.87368675 92.91912533H75.268096A40.90611485 40.90611485 0 0 1 34.31537778 51.96640711 40.90611485 40.90611485 0 0 1 75.268096 11.01368889h874.60559075a40.90611485 40.90611485 0 0 1 40.95271823 40.95271822 40.90611485 40.90611485 0 0 1-40.95271823 40.95271822z"
                    p-id="889"
                  ></path>
                </svg>
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="55" size="large" />
          <el-table-column prop="fileName" label="文档名称" width="180">
            <template #header>
              <div style="width: 100%; text-align: left">文档名称</div>
            </template>
            <template #default="scope">
              <div
                style="display: flex; align-items: center"
                :title="htmlTotext(scope.row.fileName)"
              >
                <el-icon>
                  <document />
                </el-icon>
                <!-- <span style="margin-left: 10px">{{ scope.row.fileName }}</span> -->
                <span
                  style="margin-left: 10px"
                  v-html="scope.row.fileName"
                ></span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="member" label="成员" v-if="pageFrom=='myfolder'">
            <template #default="scope">
              <span
                v-html="scope.row.member"
                :title="htmlTotext(scope.row.member)"
              ></span>
            </template>
          </el-table-column>
          <el-table-column prop="htmlStructure" label="流程">
            <template #default="">
              <!-- <el-button type="primary" size="small" link>
                {{ scope.row.address }}
              </el-button> -->
              <span>流程</span>
              <!-- <span v-html="scope.row.htmlStructure"></span> -->
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="updateTime" label="更新时间" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-dropdown placement="bottom" popper-class="opeDropdown">
                <el-button
                  link
                  size="small"
                  :icon="More"
                  class="moreBtn"
                  @click="(e) => e.preventDefault()"
                >
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="item in opebuttonList"
                      :key="item.label"
                      @click="item.onClick(scope.row)"
                    >
                      <el-button
                        link
                        :icon="item.icon"
                        :type="
                          item.label == '置顶' && scope.row.isTop == 1
                            ? 'warning'
                            : item.type
                        "
                      >
                        <template
                          v-if="item.label == '置顶' && scope.row.isTop == 1"
                          >取消</template
                        >{{ item.label }}
                      </el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <WorkFlow1
        v-if="workFlowVisible"
        :visible="workFlowVisible"
        :row="curdata"
        @close="workFlowVisible = false"
        @callback="ChangeWorkFlow"
      />
      <MemberAssignment1
        v-if="memberVisible"
        :visible="memberVisible"
        :row="curdata"
        structure="file"
        @close="memberVisible = false"
        @update="
          () => {
            memberVisible = false;
            getFileList();
          }
        "
      />
      <el-dialog
        title="修改文档信息"
        v-model="editdialogVisible"
        width="400px"
        @close="resetForm"
      >
        <el-form :model="editingForm" ref="editingFormRef" label-width="auto">
          <el-form-item label="文档名称">
            <el-input
              v-model="editingForm.fileName"
              placeholder="请输入文档名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="editingForm.remark"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="editdialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="propvisible" title="文档属性"> 属性内容 </el-dialog>
    </template>
  </Dividetb>
</template>
<script setup>
import { ref, toRaw, onMounted } from "vue";
import { debounce } from "lodash-es";
import {
  More,
  FolderOpened,
  Top,
  EditPen,
  Delete,
  SetUp,
  Edit,
} from "@element-plus/icons-vue";
import { useRoute } from "vue-router";
import NewWindow from "@/assets/customIcon/NewWindow.vue";
import WorkFlowIcon from "@/assets/customIcon/WorkFlow.vue";
import MemberAssignmentIcon from "@/assets/customIcon/MemberAssignment.vue";
import useTagStore from "@/stores/tagList";
import Dividetb from "@/layout/components/dividetb.vue";
import TopBox from "@/components/TopTitleBox/index.vue";
import FilterSearch from "@/components/TopTitleBox/FilterSearch.vue";
import topButtonGroup from "@/components/ButtonGroup/topButtonGroup.vue";
import topButtonGroupDoc from "@/components/ButtonGroup/topButtonGroupDoc.vue";
import NewFile from "../components/NewFile.vue";
import AddToKnowledgeLib from "../components/AddToKnowledgeLib.vue";
import AddToTemplate from "../components/AddToTemplateLib.vue";
import WorkFlow1 from "../components/WorkFlow1.vue";
import MemberAssignment1 from "../components/MemberAssignment1.vue";
import {
  getDocumentList,
  deleteDocument,
  updateDocumentName,
  topDocumentId,
  addPersonalTemplateDoc,
  addDocumentToKnowLib,
} from "@/api/document.js";
import {
  addPersonalTemplateFolder,
  updatePersonalTemplateFolder,
  topPersonalTemplateFolder,
  deleteTemplate,
  getPersonageTemplateFile,
} from "@/api/template.js";
import { cellMouseEnter, cellMouseLeave } from "@/utils/cellmouseEvent.js";
import { loading } from "@/utils/topButton.js";
import { htmlTotext } from "@/utils/getData.js";
defineOptions({ name: "MyFolder" });
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
// 路由传递的参数
const route = useRoute();
let queryfolderId, queryfolderName, queryfolderModelId, pageFrom;
// 分页器与筛选条件
const total = ref(0);
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
});
const filtrateFormData = reactive({
  delFlag: "0",
});
// 新增文档
const newFileVisible = ref(false);
const newCallBack = () => {
  // 创建完成后调用的函数
};
// 关闭新增文档弹窗
const closeNewFile = async () => {
  newFileVisible.value = false;
  getFileList();
};
// 滚动事件处理（带防抖）
const handleScroll = debounce((e) => {
  console.log("滚动事件触发", e);
  // 距离底部 300px 时触发
  const bottomThreshold = 300;
  const container = document.querySelector(".listTable .el-scrollbar");
  const parent = document.querySelector(".listTable tbody");
  console.log(container, parent);
  const conRect = container.getBoundingClientRect();
  const parentRect = parent.getBoundingClientRect();
  console.log(conRect, parentRect);
  if (parentRect.bottom - conRect.bottom <= bottomThreshold) {
    console.log("到底了");
    loadMore();
  }
}, 100);

const loadMore = () => {
  if (!hasMore.value || tableLoading.value) return;
  // 获取下一页列表数据
  getFileList();
};

const tagStore = useTagStore();
const tableData = ref([]);
const isLoading = ref(false);
const editdialogVisible = ref(false);
const resetForm = () => {
  editdialogVisible.value = false;
};
const editingForm = ref({});
const submitForm = () => {
  // 校验editingForm中的值是否齐全
  if (editingForm.value.fileName == "" || editingForm.value.fileName == null) {
    ElMessage({
      message: "请输入文档名称",
      type: "error",
    });
    return;
  }
  // 调用接口修改文档信息
  updateDocumentName(editingForm.value).then((res) => {
    if (res.code == 200) {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
      editdialogVisible.value = false;
      // regainData();
      getFileList(); // 重新获取列表数据
    }
  });
};
// 按钮列表
const tbuttonList = ref([
  {
    label: "回退",
    icon: "el-icon-back",
    type: "b2",
    onClick: () => {
      // router.go(-1)
      console.log("点击了回退");
      tagStore.historyBack({
        name: `/document/l/files?id=${queryfolderId}&name=${queryfolderName}&pageFrom=${pageFrom}&modelId=${queryfolderModelId}`,
        breadcrumbName: queryfolderName,
      });
    },
  },
  {
    label: "前进",
    icon: "el-icon-right",
    type: "b2",
    onClick: () => {
      // router.go(1)
      console.log("点击了前进");
      tagStore.historyFoward({
        name: `/document/l/files?id=${queryfolderId}&name=${queryfolderName}&pageFrom=${pageFrom}&modelId=${queryfolderModelId}`,
        breadcrumbName: queryfolderName,
      });
    },
  },
  {
    label: "添加",
    icon: "el-icon-CirclePlus",
    type: "b2",
    onClick: () => {
      console.log("点击了添加");
      // 打开弹窗
      newFileVisible.value = true;
    },
  },
  {
    label: "刷新",
    icon: "el-icon-refresh",
    type: "b2",
    onClick: (e) => {
      console.log("点击了刷新");
      // 清空搜索条件
      // delete filtrateFormData.params;
      // filterSearchRef.value.reset();
      loading(e, () => {
        return new Promise((resolve) => {
          // 清空表格数据
          // tableData.value = [];
          isLoading.value = true;
          // 重新获取列表数据
          getFileList().then(() => {
            isLoading.value = false;
            ElMessage.success("刷新成功");
            resolve();
          });
        });
      });
    },
  },
  {
    label: "评论",
    icon: "el-icon-ChatDotRound",
    type: "b2",
    onClick: () => {
      console.log("点击了评论");
    },
  },
  {
    label: "审批",
    icon: "el-icon-stamp",
    type: "b2",
    onClick: () => {
      console.log("点击了审批");
    },
  },
  {
    label: "添加知识库",
    icon: "el-icon-Collection",
    type: "b2",
    onClick: () => {
      console.log("点击了添加到知识库");
      console.log(once.value, selectedFileIds.value);
      if (once.value) {
        AddToKnowledge();
      } else {
        if (selectedFileIds.value.length == 0) {
          ElMessage.info("请选择要添加至知识库的文档");
        } else {
          ElMessage.info("一次只能添加一个文档到知识库");
        }
      }
    },
  },
  {
    label: "添加模板",
    icon: "AddTemplate",
    type: "b2",
    onClick: () => {
      console.log("点击了添加到模板");
      console.log(once.value);
      if (once.value) {
        AddToTem();
      } else {
        if (selectedFileIds.value.length == 0) {
          ElMessage.info("请选择要添加至模板的文件夹");
        } else {
          ElMessage.info("一次只能添加一个文件夹到模板");
        }
      }
    },
  },
  {
    label: "批量删除",
    icon: "el-icon-delete",
    type: "b2",
    onClick: () => {
      console.log("点击了批量删除");
      const selectedRows = tableRef.value.getSelectionRows();
      if (!selectedRows.length) {
        ElMessage.warning("请勾选一条数据!");
        return;
      }
      console.log("选中的行:", selectedRows);
      ElMessageBox.confirm(`确定要删除这些文档吗？`, "", {
        dangerouslyUseHTMLString: true,
      }).then(() => {
        deleteDocument(selectedRows.map((e) => e.id).join(",")).then(
          async (res) => {
            console.log(res);
            if (res.code !== 200) return;
            ElMessage.success("删除文档成功!");
            // 删除成功后，重新获取列表数据
            getFileList();
          }
        );
      });
    },
  },
  // {
  //   label: "列表视图切换",
  //   icon: "FaAlignJustify",
  //   type: "b2",
  //   onClick: () => {
  //     console.log("点击了回收站");
  //   },
  // },
]);
const opebuttonList = [
  {
    icon: FolderOpened,
    label: "打开",
    onClick: (row) => {
      openFile(row);
    },
  },
  {
    icon: SetUp,
    label: "属性",
    onClick: (row) => {
      attribute(row);
    },
  },
  {
    icon: WorkFlowIcon,
    label: "流程配置",
    onClick: (row) => {
      console.log("流程", row);
      curdata.value = row;
      // 打开弹窗
      workFlowVisible.value = true;
    },
  },
  {
    icon: MemberAssignmentIcon,
    label: "成员分配",
    onClick: (row) => {
      // console.log("成员", row);
      curdata.value = row;
      // 打开弹窗
      memberVisible.value = true;
    },
  },
  {
    icon: EditPen,
    label: "重命名",
    onClick: (row) => {
      ElMessageBox.prompt("请输入新的文档名称", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "文档名称不能为空",
      })
        .then(({ value }) => {
          console.log("重命名", value);
          // 调用重命名接口
          updateDocumentName({
            id: row.id,
            fileName: value,
            folderId: route.query?.id || "",
          }).then(async (res) => {
            if (res.code !== 200) return;
            ElMessage.success("重命名成功!");
            getFileList();
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
  },
  {
    icon: Edit,
    label: "修改文档信息",
    onClick: (row) => {
      console.log(row);
      editdialogVisible.value = true;
      editingForm.value = {
        id: row.id,
        fileName: row.fileName,
        remark: row.remark,
        folderId: row.folderId,
      };
    },
  },
  {
    icon: Top,
    label: "置顶",
    onClick: (row) => {
      console.log("成员", row);
      topDocumentId({ id: row.id }).then((res) => {
        if (res.code !== 200) return;
        if (row.isTop == 1) {
          ElMessage.success("取消置顶成功!");
        } else {
          ElMessage.success("置顶操作成功!");
        }
        getFileList();
      });
    },
  },
  {
    icon: Delete,
    label: "删除",
    type: "danger",
    onClick: (row) => {
      console.log("删除文档", row);
      ElMessageBox.confirm(`确定要删除文档${row.fileName}吗？`, "", {
        dangerouslyUseHTMLString: true,
      }).then(() => {
        deleteDocument(row.id).then(async (res) => {
          console.log(res);
          if (res.code !== 200) return;
          ElMessage.success("删除文档成功!");

          // 清除已打开文档
          // console.log(tagStore.getFullPathTag(`/fileEdit?id=${row.id}&name=${row.fileName}`), '238917391');
          let index = tagStore.tagList.findIndex(
            (item) =>
              item.fullPath === `/fileEdit?id=${row.id}&name=${row.fileName}`
          );
          if (index >= 0) {
            tagStore.deleteTagList(index);
          }

          // 删除成功后，重新获取列表数据
          getFileList();
        });
      });
    },
  },
];
const filterSearchRef = ref(null); // 搜索组件
const searchCallBack = (word, time) => {
  console.log("搜索回调", word, time);
  let params = {};
  if (word) {
    params.searchKey = word;
  }
  if (time) {
    params.startTime = time[0] ? time[0] + " 00:00:00" : null;
    params.endTime = time[1] ? time[1] + " 23:59:59" : null;
  }
  filtrateFormData.params = params;
  pagination.pageNum = 1; // 重置页码
  getFileList();
};
const openFile = (row) => {
  console.log("打开", row);
  router.push({
    name: "fileEdit",
    query: {
      id: row.id,
      name: row.fileName,
    },
  });
  tagStore.addTagList({
    name: `/fileEdit`,
    fullPath: `/fileEdit?id=${row.id}&name=${row.fileName}`,
    breadcrumbName: row.fileName,
    historyList: [],
  });
};
const addToFileId = ref();
const addToFileName = ref("");
let addToFileData;
// 添加知识库
const addToVisible = ref(false);
// 确认添加
const addToCallback = (fileName, fileRemark, folderId) => {
  console.log(fileName, fileRemark, folderId);
  return new Promise((resolve, reject) => {
    addDocumentToKnowLib({
      fileName,
      remark: fileRemark,
      folderId: folderId,
      documentId: addToFileId.value,
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
// 打开弹窗
const AddToKnowledge = (row) => {
  console.log(row);
  if (row) {
    addToFileName.value = row.fileName;
    addToFileId.value = row.id;
  } else {
    addToFileName.value = tableData.value.find(
      (item) => item.id == selectedFileIds.value[0]
    ).fileName;
    addToFileId.value = selectedFileIds.value[0];
  }
  addToVisible.value = true;
};
// 添加个人模板
const addTemVisible = ref(false);
const addTemCallback = (temName, temRemark) => {
  console.log(temName, temRemark);
  //執行回調，调用接口添加个人模板
  return new Promise((resolve, reject) => {
    const folderId = route.query?.id || "";
    if (!folderId) {
      ElMessage.error("获取文件夹id失败，请刷新页面重试");
      reject();
      return;
    }
    console.log(addToFileData);
    addPersonalTemplateDoc({
      fileName: temName,
      remark: temRemark,
      folderId,
      documentId: addToFileId.value,
      xmlStructure: addToFileData.xmlStructure,
      htmlStructure: addToFileData.htmlStructure,
      isTop: 0,
      source: 0, // 0我的文档 1知识库
    })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
const AddToTem = (row) => {
  if (row) {
    addToFileName.value = row.fileName;
    addToFileId.value = row.id;
    addToFileData = row;
  } else {
    addToFileName.value = tableData.value.find(
      (item) => item.id == selectedFileIds.value[0]
    ).fileName;
    addToFileId.value = selectedFileIds.value[0];
    addToFileData = tableData.value.find(
      (item) => item.id == selectedFileIds.value[0]
    );
  }
  addTemVisible.value = true;
};
// 查看文档属性
const propvisible = ref(false);
const attribute = (row) => {
  console.log(row);
  propvisible.value = true;
};
// 流程配置
const workFlowVisible = ref(false);
const curdata = ref({});
const ChangeWorkFlow = (val) => {
  ElMessage.info("调用接口修改流程配置");
};
// 成员分配
const memberVisible = ref(false);
// 获取列表数据
const getFileList = async (data = {}) => {
  const folderId = route.query?.id || "";
  let params = {
    ...pagination,
    ...filtrateFormData,
    ...data,
    folderId,
  };
  console.log(params, "获取列表数据1");
  if (pageFrom == "myfolder") {
    await getDocumentList({ ...params }).then((res) => {
      if (res.code === 200) {
        console.log(res.rows, "获取列表数据2");
        tableData.value = res.rows;
        total.value = res.total;
      }
    });
  } else if (pageFrom == "mytemplate") {
    await getPersonageTemplateFile({ ...params }).then((res) => {
      if (res.code === 200) {
        console.log(res.rows, "获取列表数据2");
        tableData.value = res.rows;
        total.value = res.total;
      }
    });
  }
};
const tableRef = ref(null);
const selectedFileIds = ref([]); // 多选框选中数据
const multiple = ref(true); // 是否多选
const once = ref(false); //是否单选
const curFile = ref("");
// 多选框选中数据
function handleSelectionChange(selection) {
  selectedFileIds.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
  if (selection.length == 1) {
    once.value = true;
  } else {
    once.value = false;
  }
}
const currentRowChange = (curRow) => {
  console.log(curRow);
  const flag = selectedFileIds.value.includes(curRow.id);
  tableRef.value.toggleRowSelection(curRow, !flag);
  curFile.value = curRow.fileName;

  // openFile(curRow);
};
onMounted(async () => {
  console.log("文档管理页面挂载完成");
  queryfolderId = route.query.id;
  queryfolderName = route.query.name;
  queryfolderModelId = route.query.modelId;
  pageFrom = route.query.pageFrom;
  // 调用接口获取数据
  await getFileList();
});
</script>
<style lang="scss" scoped>
.tableBox {
  :deep(.cell) {
    display: flex;
    justify-content: center;
    font-size: var(--el-font-size-base);
    & > div {
      width: 100%;
      & > span {
        flex: 1;
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        text-align: left;
      }
    }
  }
  :deep(.zhiding) {
    border-bottom: none !important;
  }
  .moreBtn {
    display: none;
    &.active {
      display: flex;
    }
  }
}
.opeDropdown {
  button {
    width: 100%;
    justify-content: start;
  }
}
</style>
